package com.dylan.历史.基础;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * @author : ankang
 * @date : 2020/3/7 22:00
 * @Description : 自建构建器，适用于各种pojo、DTO、domain
 */
public class Builder<T> {
    private final Supplier<T> instance;
    private List<Consumer<T>> modifierList = new ArrayList<>();

    private Builder(Supplier<T> instance) {
        this.instance = instance;
    }

    public static <T> Builder<T> of(Supplier<T> instance) {
        return new Builder<>(instance);
    }

    public <P1> Builder<T> with(Consumer1<T, P1> consumer1, P1 p1) {
        Consumer<T> modifier = t -> consumer1.accept(t, p1);
        modifierList.add(modifier);
        return this;
    }

    public <P1, P2> Builder<T> with(Consumer2<T, P1, P2> consumer2, P1 p1, P2 p2) {
        Consumer<T> modifier = t -> consumer2.accept(t, p1, p2);
        modifierList.add(modifier);
        return this;
    }

    public <P1, P2, P3> Builder<T> with(Consumer3<T, P1, P2, P3> consumer3, P1 p1, P2 p2, P3 p3) {
        Consumer<T> modifier = t -> consumer3.accept(t, p1, p2, p3);
        modifierList.add(modifier);
        return this;
    }

    public T build() {
        T t = instance.get();
        modifierList.forEach(m -> m.accept(t));
        modifierList.clear();
        return t;
    }

    @FunctionalInterface
    public interface Consumer1<T, P1> {
        void accept(T t, P1 p1);
    }

    @FunctionalInterface
    public interface Consumer2<T, P1, P2> {
        void accept(T t, P1 p1, P2 p2);
    }

    @FunctionalInterface
    public interface Consumer3<T, P1, P2, P3> {
        void accept(T t, P1 p1, P2 p2, P3 p3);
    }
}
